<template>
    <div style="margin-top: 20px; width: 100%">
        <el-form :inline="true" :model="ruleForm" style="font-size: 15px; width: 100%" class="query-form">
            <div class="query-row">
                <el-form-item label="报工类型">
                    <el-select v-model="page.reportTypeId" placeholder="请选择报工类型" size="large" filterable>
                        <el-option label="自行报工" :value="1" />
                        <el-option label="统一报工" :value="2" />
                    </el-select>
                </el-form-item>
                <el-form-item label="生产工单编号" style="margin-left: -20px">
                    <el-input v-model="page.productionId" />
                </el-form-item>
                <el-form-item label="产品物料编码" style="margin-left: 20px">
                    <el-input v-model="page.productMaterialCode" />
                </el-form-item>
            </div>
            <div class="query-row">
                <el-form-item label="产品物料名称" style="margin-left: -20px">
                    <el-input v-model="page.productMaterialName" />
                </el-form-item>
                <el-form-item label="报工人" style="margin-left: 20px">
                    <el-input v-model="page.caller" />
                </el-form-item>
                <el-form-item label="状态" style="margin-left: 20px">
                    <el-select v-model="page.status" placeholder="请选择供应商" size="large" filterable>
                        <el-option label="草稿" :value="1" checked />
                        <el-option label="已确认" :value="2" />
                        <el-option label="审批中" :value="3" />
                        <el-option label="已审批" :value="4" />
                        <el-option label="已完成" :value="5" />
                    </el-select>
                </el-form-item>
            </div>
            <el-form-item>
                <el-button type="primary" @click="fetchData">查询</el-button>
                <el-button type="primary" @click="empty">清空</el-button>
            </el-form-item>
        </el-form>
    </div>
    <div style="width: 500px">
        <el-button type="primary" @click="AddProudct()" style="width: 100px">新增</el-button>
        <el-button type="primary" @click="Derive()" style="width: 100px">导出</el-button>
        <el-button type="primary" @click="Leadinto()" style="width: 100px">导入</el-button>
    </div>

    <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="reportTypeId" label="报工类型">
            <template #default="scope">
                <span v-if="scope.row.reportTypeId == 1">自行报工</span>
                <span v-if="scope.row.reportTypeId == 2">统一报工</span>
            </template>
        </el-table-column>
        <el-table-column prop="workStation" label="工作站" />
        <el-table-column prop="productionId" label="生产工单编号" />
        <el-table-column prop="productMaterialCode" label="产品物料编码" />
        <el-table-column prop="productMaterialName" label="产品物料名称" />
        <el-table-column prop="specificationModel" label="规格型号" />
        <el-table-column prop="quantityReported" label="报工数量" />
        <el-table-column prop="caller" label="报工人" />
        <el-table-column prop="callTime" label="报工时间" />
        <el-table-column prop="auditor" label="审核人" />
        <el-table-column prop="status" label="状态">
            <template #default="scope">
                <span v-if="scope.row.status == 1">草稿</span>
                <span v-if="scope.row.status == 2">已确认</span>
                <span v-if="scope.row.status == 3">审批中</span>
                <span v-if="scope.row.status == 4">已审批</span>
                <span v-if="scope.row.status == 5">已完成</span>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
            <template #default="scope">
                <el-button size="small" @click="editItem(scope.row)">编辑</el-button>
                <el-button size="small" @click="Creadeinfo(scope.row.productionReportId)">审批</el-button>
                <el-button size="small" @click="DelFrom(scope.row.productionReportId)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <div>
        <el-pagination v-model:current-page="page.PageIndex" v-model:page-size="page.PageSize"
            :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" :total="page.totalCount"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <div>
        <el-dialog v-model="dialogFormVisible" title="添加生产报工" width="1000">
            <el-form ref="ruleFormRef" style="max-width: 900px" :model="ruleForm" label-width="auto"
                class="demo-ruleForm" :size="formSize" status-icon>
                <div style="display: flex; flex-wrap: wrap;">
                    <!-- 控制每行显示3个常规输入项 -->
                    <el-form-item label="报工类型" prop="reportTypeId" style="flex: 0 0 33.33%; max-width: 33.33%;">
                        <el-select v-model="ruleForm.reportTypeId" placeholder="请选择报工类型" size="large" filterable>
                            <el-option label="统一报工" :value="1" />
                            <el-option label="自行报工" :value="2" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="生产工单" prop="productionId" style="flex: 0 0 33.33%; max-width: 33.33%;">
                        <el-input v-model="ruleForm.productionId" />
                        <el-button type="primary" @click="product()">生产工单</el-button>
                    </el-form-item>
                    <el-form-item label="生产任务" prop="productionTaskNumber" style="flex: 0 0 33.33%; max-width: 33.33%;">
                        <el-input v-model="ruleForm.productionTaskNumber" />
                        <el-button type="primary" @click="redsinfo()">生产任务</el-button>
                    </el-form-item>
                    <el-form-item label="产品编码" prop="productMaterialCode" style="flex: 0 0 33.33%; max-width: 33.33%;">
                        <el-input v-model="ruleForm.productMaterialCode" />
                    </el-form-item>
                    <el-form-item label="产品名称" prop="productMaterialName" style="flex: 0 0 33.33%; max-width: 33.33%;">
                        <el-input v-model="ruleForm.productMaterialName" />
                    </el-form-item>
                    <el-form-item label="单位" prop="unit" style="flex: 0 0 33.33%; max-width: 33.33%;">
                        <el-input v-model="ruleForm.unit" />
                    </el-form-item>
                    <el-form-item label="规格型号" prop="specificationModel" style="width: 100%;">
                        <el-input v-model="ruleForm.specificationModel" type="textarea" />
                    </el-form-item>
                    <el-form-item label="待检测数量" prop="quantityReported" style="flex: 0 0 33.33%; max-width: 33.33%;">
                        <el-input-number v-model="ruleForm.quantityReported" :min="1" :max="10000000" />
                    </el-form-item>
                    <el-form-item label="报工人" prop="caller" style="flex: 0 0 33.33%; max-width: 33.33%;">
                        <el-input v-model="ruleForm.caller" />
                        <el-button type="primary" @click="ren()">人员信息</el-button>
                    </el-form-item>
                    <el-form-item label="报工时间" prop="callTime" style="flex: 0 0 33.33%; max-width: 33.33%;">
                        <el-date-picker v-model="ruleForm.callTime" type="datetime"
                            placeholder="Select date and time" />
                    </el-form-item>
                    <el-form-item label="审核人" prop="auditor" style="width: 100%;">
                        <el-input v-model="ruleForm.auditor" />
                        <el-button type="primary" @click="ren1()">审核人</el-button>
                    </el-form-item>
                </div>
                <!-- 富文本单独占一行 -->
                <el-form-item label="备注" prop="remark" style="width: 100%;">
                    <el-input v-model="ruleForm.remark" type="textarea" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="AddForm(ruleFormRef)">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>


    <div>
        <el-dialog v-model="dialogFormVisible2" title="显示生产任务" width="1000">
            <div style="margin-top: 20px; width: 100%">
                <el-form :inline="true" :model="ruleForm" style="font-size: 15px; width: 100%" class="query-form">
                    <el-form-item label="所属工作站" style="margin-left: 20px">
                        <el-input v-model="page1.workStationNumber" />
                    </el-form-item>
                    <el-form-item label="任务编号" style="margin-left: 20px">
                        <el-input v-model="page1.taskNumber" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="ShowProduct">查询</el-button>
                        <el-button type="primary" @click="empty1">清空</el-button>
                    </el-form-item>
                </el-form>
            </div>

            <el-table :data="tableData1" border style="width: 100%">
                <el-table-column label="选择" width="30">
                    <template #default="scope">
                        <el-radio v-model="selectedRow" :label="scope.row"></el-radio>
                    </template>
                </el-table-column>
                <el-table-column prop="taskNumber" label="任务编号" />
                <el-table-column prop="taskName" label="任务名称" />
                <el-table-column prop="workStationNumber" label="工作站编号" />
                <el-table-column prop="workStationName" label="工作站名称" />
                <el-table-column prop="scheduledNumber" label="排产数量" />
                <el-table-column prop="quantityProduced" label="已生产数量" />
                <el-table-column prop="startofProductionTime" label="开始生产时间" />
                <el-table-column prop="productionTime" label="生产时长" />
                <el-table-column prop="estimatedTime" label="预计完成时间" />
                <el-table-column prop="displayColor" label="显示颜色" />
                <el-table-column label="操作" width="100">
                    <template #default="scope">
                        <el-button size="small" @click="DelProduct(scope.row.productionTaskId)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div>
                <el-pagination v-model:current-page="page1.PageIndex" v-model:page-size="page1.PageSize"
                    :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper"
                    :total="page1.totalCount" @size-change="handleSizeChange1" @current-change="handleCurrentChange1" />
            </div>
            <el-button type="primary" @click="AddProudctInfo()">确定</el-button>
            <el-button type="primary" @click="dialogFormVisible2 = false">取消</el-button>
        </el-dialog>

    </div>
    <div>
        <el-dialog v-model="dialogFormVisible3" title="显示生产工单" width="1000">
            <div style="margin-top: 20px; width: 100%">
                <el-form :inline="true" :model="ruleForm" style="font-size: 15px; width: 100%" class="query-form">
                    <el-form-item label="工单编号" style="margin-left: 30px">
                        <el-input v-model="page3.workOrderCoding" />
                    </el-form-item>
                    <el-form-item label="工单名称" style="margin-left: 20px">
                        <el-input v-model="page3.workOrderName" />
                    </el-form-item>
                    <el-form-item label="产品编号" style="margin-left: 20px">
                        <el-input v-model="page3.productNumber" />
                    </el-form-item>
                    <el-form-item label="产品名称" style="margin-left: 20px">
                        <el-input v-model="page3.productName" />
                    </el-form-item>
                    <el-form-item label="客户名称" style="margin-left: 20px">
                        <el-input v-model="page3.customerNamwe" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="fetchData3">查询</el-button>
                        <el-button type="primary" @click="empty3">清空</el-button>
                    </el-form-item>
                </el-form>
            </div>

            <el-table :data="tableData2" border style="width: 100%">
                <el-table-column label="选择" width="30">
                    <template #default="scope">
                        <el-radio v-model="selectedRow" :label="scope.row"></el-radio>
                    </template>
                </el-table-column>
                <el-table-column prop="workOrderCoding" label="工单编号" />
                <el-table-column prop="workOrderName" label="工单名称" />
                <el-table-column prop="workOrderType" label="工单来源" />
                <el-table-column prop="orderNumber" label="订单编号" />
                <el-table-column prop="productNumber" label="产品编号" />
                <el-table-column prop="productName" label="产品名称" />
                <el-table-column prop="specifications" label="规格型号" />
                <el-table-column prop="unit" label="单位" />
                <el-table-column prop="customerCode" label="客户编码" />
                <el-table-column prop="customerNamwe" label="客户名称" />
            </el-table>
            <div>
                <el-pagination v-model:current-page="page3.index" v-model:page-size="page3.size"
                    :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper"
                    :total="page3.totalCount" @size-change="handleSizeChange3" @current-change="handleCurrentChang3" />
            </div>
            <el-button type="primary" @click="AddGongdan()">确定</el-button>
            <el-button type="primary" @click="dialogFormVisible3 = false">取消</el-button>
        </el-dialog>

    </div>
    <div>
        <el-dialog v-model="dialogFormVisible4" title="显示人员信息" width="1000">
            <div style="margin-top: 20px; width: 100%">
                <el-form :inline="true" :model="ruleForm" style="font-size: 15px; width: 100%" class="query-form">
                    <el-form-item label="用户名称">
                        <el-input v-model="page2.userName" />
                    </el-form-item>
                    <el-form-item label="手机号码" style="margin-left: -20px">
                        <el-input v-model="page2.phone" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="fetchData2">查询</el-button>
                        <el-button type="primary" @click="empty2">清空</el-button>
                    </el-form-item>
                </el-form>
            </div>

            <el-table :data="tableData3" border style="width: 100%">
                <el-table-column label="选择" width="30">
                    <template #default="scope">
                        <el-radio v-model="selectedRow" :label="scope.row"></el-radio>
                    </template>
                </el-table-column>
                <el-table-column prop="userName" label="用户名称" />
                <el-table-column prop="userNickname" label="用户昵称" />
                <el-table-column prop="section" label="部门" />
                <el-table-column prop="phone" label="手机号码" />
                <el-table-column prop="creationTime" label="创建时间" />
            </el-table>
            <div>
                <el-pagination v-model:current-page="page2.PageIndex" v-model:page-size="page2.PageSize"
                    :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper"
                    :total="page2.totalCount" @size-change="handleSizeChange2" @current-change="handleCurrentChang2" />
            </div>
            <el-button type="primary" @click="Addren()">确定</el-button>
            <el-button type="primary" @click="dialogFormVisible4 = false">取消</el-button>
        </el-dialog>

    </div>

    <div>
        <el-dialog v-model="dialogFormVisible1" title="显示人员信息" width="1000">
            <div style="margin-top: 20px; width: 100%">
                <el-form :inline="true" :model="ruleForm" style="font-size: 15px; width: 100%" class="query-form">
                    <el-form-item label="用户名称">
                        <el-input v-model="page2.userName" />
                    </el-form-item>
                    <el-form-item label="手机号码" style="margin-left: -20px">
                        <el-input v-model="page2.phone" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="fetchData2">查询</el-button>
                        <el-button type="primary" @click="empty2">清空</el-button>
                    </el-form-item>
                </el-form>
            </div>

            <el-table :data="tableData3" border style="width: 100%">
                <el-table-column label="选择" width="30">
                    <template #default="scope">
                        <el-radio v-model="selectedRow" :label="scope.row"></el-radio>
                    </template>
                </el-table-column>
                <el-table-column prop="userName" label="用户名称" />
                <el-table-column prop="userNickname" label="用户昵称" />
                <el-table-column prop="section" label="部门" />
                <el-table-column prop="phone" label="手机号码" />
                <el-table-column prop="creationTime" label="创建时间" />
            </el-table>
            <div>
                <el-pagination v-model:current-page="page2.PageIndex" v-model:page-size="page2.PageSize"
                    :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper"
                    :total="page2.totalCount" @size-change="handleSizeChange2" @current-change="handleCurrentChang2" />
            </div>
            <el-button type="primary" @click="Addren1()">确定</el-button>
            <el-button type="primary" @click="dialogFormVisible4 = false">取消</el-button>
        </el-dialog>

    </div>

    <div>
        <el-dialog v-model="dialogFormVisible5" title="修改生产报工" width="1000">
            <el-form ref="ruleFormRef" style="max-width: 900px" :model="ruleForm" label-width="auto"
                class="demo-ruleForm" :size="formSize" status-icon>
                <div style="display: flex; flex-wrap: wrap;">
                    <!-- 控制每行显示3个常规输入项 -->
                    <el-form-item label="报工类型" prop="reportTypeId" style="flex: 0 0 33.33%; max-width: 33.33%;">
                        <el-select v-model="ruleForm.reportTypeId" placeholder="请选择报工类型" size="large" filterable>
                            <el-option label="统一报工" :value="1" />
                            <el-option label="自行报工" :value="2" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="生产工单" prop="productionId" style="flex: 0 0 33.33%; max-width: 33.33%;">
                        <el-input v-model="ruleForm.productionId" />
                        <el-button type="primary" @click="product()">生产工单</el-button>
                    </el-form-item>
                    <el-form-item label="生产任务" prop="productionTaskNumber" style="flex: 0 0 33.33%; max-width: 33.33%;">
                        <el-input v-model="ruleForm.productionTaskNumber" />
                        <el-button type="primary" @click="redsinfo()">生产任务</el-button>
                    </el-form-item>
                    <el-form-item label="产品编码" prop="productMaterialCode" style="flex: 0 0 33.33%; max-width: 33.33%;">
                        <el-input v-model="ruleForm.productMaterialCode" />
                    </el-form-item>
                    <el-form-item label="产品名称" prop="productMaterialName" style="flex: 0 0 33.33%; max-width: 33.33%;">
                        <el-input v-model="ruleForm.productMaterialName" />
                    </el-form-item>
                    <el-form-item label="单位" prop="unit" style="flex: 0 0 33.33%; max-width: 33.33%;">
                        <el-input v-model="ruleForm.unit" />
                    </el-form-item>
                    <el-form-item label="规格型号" prop="specificationModel" style="width: 100%;">
                        <el-input v-model="ruleForm.specificationModel" type="textarea" />
                    </el-form-item>
                    <el-form-item label="待检测数量" prop="quantityReported" style="flex: 0 0 33.33%; max-width: 33.33%;">
                        <el-input-number v-model="ruleForm.quantityReported" :min="1" :max="10000000" />
                    </el-form-item>
                    <el-form-item label="报工人" prop="caller" style="flex: 0 0 33.33%; max-width: 33.33%;">
                        <el-input v-model="ruleForm.caller" />
                        <el-button type="primary" @click="ren()">人员信息</el-button>
                    </el-form-item>
                    <el-form-item label="报工时间" prop="callTime" style="flex: 0 0 33.33%; max-width: 33.33%;">
                        <el-date-picker v-model="ruleForm.callTime" type="datetime"
                            placeholder="Select date and time" />
                    </el-form-item>
                    <el-form-item label="审核人" prop="auditor" style="width: 100%;">
                        <el-input v-model="ruleForm.auditor" />
                        <el-button type="primary" @click="ren1()">审核人</el-button>
                    </el-form-item>
                </div>
                <!-- 富文本单独占一行 -->
                <el-form-item label="备注" prop="remark" style="width: 100%;">
                    <el-input v-model="ruleForm.remark" type="textarea" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible5 = false">取消</el-button>
                    <el-button type="primary" @click="UpdateForm(ruleFormRef)">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import axios from 'axios';
import { ElMessage, ElMessageBox, ElTable, ElTableColumn, ElPagination } from 'element-plus';
import { onMounted, ref, reactive, computed } from 'vue';
const apiUrl = import.meta.env.VITE_APP_API_URL;
const tableData = ref([]);
const tableData1 = ref([]);
const tableData2 = ref([]);
const tableData3 = ref([]);

const dialogFormVisible = ref(false)
const dialogFormVisible1 = ref(false)
const dialogFormVisible2 = ref(false)
const dialogFormVisible3 = ref(false)
const dialogFormVisible4 = ref(false)
const dialogFormVisible5 = ref(false)

const redsinfo = () => {
    dialogFormVisible2.value = true;
    ShowProduct();
}

const product = () => {
    dialogFormVisible3.value = true;
    fetchData3();
}

const ren = () => {
    dialogFormVisible4.value = true;
    fetchData2();
}


const ren1 = () => {
    dialogFormVisible1.value = true;
    fetchData2();
}

const selectedRow = ref(); // 用于存储选中的行
const AddProudctInfo = () => {
    if (selectedRow.value) {
        // 将选中的单条数据存入 sessionStorage
        sessionStorage.setItem('selectedProductionTask', JSON.stringify(selectedRow.value));
        console.log('选中的数据已存入 sessionStorage', sessionStorage.getItem('selectedProductionTask'));
    } else {
        ElMessage.warning('请选择一条生产任务数据');
    }
    dialogFormVisible2.value = false;
    // 从 sessionStorage 中获取选中的生产任务数据
    const selectedTaskData = sessionStorage.getItem('selectedProductionTask');
    if (selectedTaskData) {
        const task = JSON.parse(selectedTaskData);
        console.log('解析后的生产任务数据', task);
        if (task.taskName) {
            // 将 taskName 反填到生产任务字段
            ruleForm.productionTaskNumber = task.taskName;
            console.log('生产任务字段已反填:', ruleForm.productionTaskNumber);
        } else {
            console.log('生产任务数据中不包含 taskName 字段');
        }
    } else {
        console.log('sessionStorage 中没有选中的生产任务数据');
    }
}

const Addren = () => {
    if (selectedRow.value) {
        // 将选中的单条数据存入 sessionStorage
        sessionStorage.setItem('personnel', JSON.stringify(selectedRow.value));
        console.log('选中的数据已存入 sessionStorage', sessionStorage.getItem('personnel'));
    } else {
        ElMessage.warning('请选择一条生产任务数据');
    }
    dialogFormVisible4.value = false;
    // 从 sessionStorage 中获取选中的生产任务数据
    const selectedTaskData = sessionStorage.getItem('personnel');
    if (selectedTaskData) {
        const task = JSON.parse(selectedTaskData);
        console.log('解析后的生产任务数据', task);
        if (task.userNickname) {
            // 将 taskName 反填到生产任务字段
            ruleForm.caller = task.userNickname;
            console.log('生产任务字段已反填:', ruleForm.caller);
        } else {
            console.log('生产任务数据中不包含 taskName 字段');
        }
    } else {
        console.log('sessionStorage 中没有选中的生产任务数据');
    }
}

const Addren1 = () => {
    if (selectedRow.value) {
        // 将选中的单条数据存入 sessionStorage
        sessionStorage.setItem('personnel', JSON.stringify(selectedRow.value));
        console.log('选中的数据已存入 sessionStorage', sessionStorage.getItem('personnel'));
    } else {
        ElMessage.warning('请选择一条生产任务数据');
    }
    dialogFormVisible1.value = false;
    // 从 sessionStorage 中获取选中的生产任务数据
    const selectedTaskData = sessionStorage.getItem('personnel');
    if (selectedTaskData) {
        const task = JSON.parse(selectedTaskData);
        console.log('解析后的生产任务数据', task);
        if (task.userNickname) {
            // 将 taskName 反填到生产任务字段
            ruleForm.auditor = task.userNickname;
            console.log('生产任务字段已反填:', ruleForm.caller);
        } else {
            console.log('生产任务数据中不包含 taskName 字段');
        }
    } else {
        console.log('sessionStorage 中没有选中的生产任务数据');
    }
}

const AddGongdan = () => {
    if (selectedRow.value) {
        // 将选中的单条数据存入 sessionStorage
        sessionStorage.setItem('WorkOrder', JSON.stringify(selectedRow.value));
        console.log('选中的数据已存入 sessionStorage', sessionStorage.getItem('WorkOrder'));
    } else {
        ElMessage.warning('请选择一条生产任务数据');
    }
    dialogFormVisible3.value = false;
    // 从 sessionStorage 中获取选中的生产任务数据
    const selectedTaskData = sessionStorage.getItem('WorkOrder');
    if (selectedTaskData) {
        const task = JSON.parse(selectedTaskData);
        console.log('解析后的生产任务数据', task);
        if (task.workOrderCoding) {
            // 将 taskName 反填到生产任务字段
            ruleForm.productionId = task.workOrderCoding;
            ruleForm.productMaterialCode = task.productNumber;
            ruleForm.productMaterialName = task.productName;
            ruleForm.unit = task.unit;
            ruleForm.specificationModel = task.specifications;
            console.log('生产任务字段已反填:', ruleForm.caller);
        } else {
            console.log('生产任务数据中不包含 taskName 字段');
        }
    } else {
        console.log('sessionStorage 中没有选中的生产任务数据');
    }
}

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);

// 查询表单数据
const page3 = reactive({
    index: 1,
    size: 10,
    totalCount: 0,
    totalPage: 0,
    workOrderCoding: '',
    workOrderName: '',
    productNumber: '',
    productName: '',
    customerNamwe: '',
});

// 整合生产工单、查询和分页的方法
const fetchData3 = () => {
    axios.get(apiUrl +'/T5/WorkOrder/GetWorkOrder', { params: page3 })
        .then((res) => {
            tableData2.value = res.data.data;
            page3.totalCount = res.data.totalCount;
            page3.totalPage = res.data.totalPage;
        })
};
const handleSizeChange3 = (val: number) => {
    console.log(`${val} items per page`);
    page3.size = val;
    fetchData3();
};
const handleCurrentChang3 = (val: number) => {
    console.log(`current page: ${val}`);
    page3.index = val;
    fetchData3();
};
const empty3 = () => {
    page3.workOrderCoding = '';
    page3.workOrderName = '';
    page3.productNumber = '';
    page3.productName = '';
    page3.customerNamwe = '';
    fetchData3();
};


// 查询表单数据
const page2 = reactive({
    PageIndex: 1,
    PageSize: 10,
    totalCount: 0,
    totalPage: 0,
    userName: '',
    phone: '',
});

// 整合人员信息、查询和分页的方法
const fetchData2 = () => {
    axios.get(apiUrl +'/T5/ProductInfo/GetCaller', { params: page2 })
        .then((res) => {
            tableData3.value = res.data.data;
            page2.totalCount = res.data.totalCount;
            page2.totalPage = res.data.totalPage;
        })
};
const handleSizeChange2 = (val: number) => {
    console.log(`${val} items per page`);
    page2.PageSize = val;
    fetchData2();
};
const handleCurrentChang2 = (val: number) => {
    console.log(`current page: ${val}`);
    page2.PageIndex = val;
    fetchData2();
};
const empty2 = () => {
    page2.userName = '';
    page2.phone = '';
    fetchData2();
};


// 查询表单数据
const page1 = reactive({
    PageIndex: 1,
    PageSize: 10,
    totalCount: 0,
    totalPage: 0,
    taskNumber: '',
    workStationNumber: '',
});

// 整合显示生产任务、查询和分页的方法
const ShowProduct = () => {
    axios.get(apiUrl +'/T5/ProductInfo/GetProductionTask', { params: page1 })
        .then((res) => {
            tableData1.value = res.data.data;
            page1.totalCount = res.data.totalCount;
            page1.totalPage = res.data.totalPage;
        })
};

const handleSizeChange1 = (val: number) => {
    console.log(`${val} items per page`);
    page1.PageSize = val;
    ShowProduct();
};
const handleCurrentChange1 = (val: number) => {
    console.log(`current page: ${val}`);
    page1.PageIndex = val;
    ShowProduct();
};

const empty1 = () => {
    page1.taskNumber = '';
    page1.workStationNumber = '';
    ShowProduct();
};

//逻辑删除生产任务
const DelProduct = (productionTaskId: any) => {
    axios.put(apiUrl +'/T6/ProductInfos/DelProductionTask', { ProductionTaskId: productionTaskId })
        .then((res) => {
            if (res.data.code == 204) {
                ElMessage({
                    message: res.data.msg,
                    type: 'success',
                })
                ShowProduct();
            } else {
                ElMessage({
                    message: '删除失败',
                    type: 'error',
                })
            }
        })
}


// 查询表单数据
const page = reactive({
    PageIndex: 1,
    PageSize: 5,
    totalCount: 0,
    totalPage: 0,
    reportTypeId: '',
    productionId: '',
    productMaterialCode: '',
    productMaterialName: '',
    caller: '',
    status: '',
});

// 整合显示生产报工、查询和分页的方法
const fetchData = () => {
    axios.get(apiUrl + '/T5/ProductInfo/GetProductionReport', { params: page })
        .then((res) => {
            tableData.value = res.data.data;
            page.totalCount = res.data.totalCount;
            page.totalPage = res.data.totalPage;
        })
};
const empty = () => {
    page.reportTypeId = '';
    page.productionId = '';
    page.productMaterialCode = '';
    page.productMaterialName = '';
    page.caller = '';
    page.status = '';
    fetchData();
};

const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`);
    page.PageSize = val;
    fetchData();
};
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`);
    page.PageIndex = val;
    fetchData();
};

//逻辑删除生产报工
const DelFrom = (productionReportId: any) => {
    axios.put(apiUrl +'/T6/ProductInfos/DelProductionReport', { ProductionReportId: productionReportId })
        .then((res) => {
            if (res.data.code == 204) {
                ElMessage({
                    message: res.data.msg,
                    type: 'success',
                })
                fetchData();
            } else {
                ElMessage({
                    message: '删除失败',
                    type: 'error',
                })
            }
        })
}
//导出生产报工
const Derive = () => {
    window.location.href = apiUrl +'/T5/ProductInfo/ExeclProductionReport';
}
//导入生产报工
const Leadinto = () => {
    console.log('执行导入操作');
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.csv, .xlsx'; // 可以根据实际需求修改允许的文件类型

    input.addEventListener('change', async (event) => {
        const file = event.target.files[0];
        if (file) {
            const formData = new FormData();
            formData.append('file', file);

            const url = apiUrl+'/T6/ProductInfos/ImportProductionReport';
            try {
                const response = await fetch(url, {
                    method: 'POST',
                    body: formData
                });
                if (response.ok) {
                    ElMessage.success('导入成功');
                }


                if (!response.ok) {
                    throw new Error(`请求失败，状态码: ${response.status}`);
                }

                const result = await response.json();
                console.log('导入成功，返回结果:', result);
            } catch (error) {
                console.error('导入失败:', error);
            }
        }
    });

    input.click();
}
const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
    productionReportId: 0,
    reportTypeId: null,
    workStation: '',
    productionId: '',
    productMaterialCode: '',
    productMaterialName: '',
    specificationModel: '',
    quantityReported: null,
    caller: '',
    callTime: new Date(),
    auditor: '',
    status: 1,
    productionTaskNumber: '',
    unit: '',
    remark: '',
    isDelete: false,
})

//初始化添加弹框
const AddProudct =()=>{
    dialogFormVisible.value = true;
    ruleForm.productionReportId = 0;
    ruleForm.reportTypeId = null;
    ruleForm.workStation = '';
    ruleForm.productionId = '';
    ruleForm.productMaterialCode = '';
    ruleForm.productMaterialName = '';
    ruleForm.specificationModel = '';
    ruleForm.quantityReported = null;
    ruleForm.caller = '';
    ruleForm.callTime = new Date();
    ruleForm.auditor = '';
    ruleForm.status = null;
    ruleForm.productionTaskNumber = '';
    ruleForm.unit = '';
    ruleForm.remark = '';
    ruleForm.isDelete = false;
}

const editItem = (item) => {
    dialogFormVisible5.value = true;
    // 创建数据副本
    const itemCopy = { ...item };
    // 将副本数据复制到 ruleForm
    Object.assign(ruleForm, itemCopy);
};

const UpdateForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            // 修改为使用 axios.put 方法
            axios.put(apiUrl + '/T6/ProductInfos/UpdateProductionReport', ruleForm)
                .then(res => {
                    if (res.data.code === 206) {
                        ElMessage.success("修改成功!");
                        dialogFormVisible5.value = false;
                        fetchData();
                    } else {
                        ElMessage.error(`修改失败: ${res.data.message || '未知错误'}`);
                    }
                })
                .catch((error) => {
                    console.error('修改生产报工失败:', error);
                    ElMessage.error('修改生产报工失败，请稍后重试');
                });
        } else {

            console.log('error submit!', fields);
            ElMessage.error('表单验证失败，请检查输入内容');
        }
    });
};

const AddForm = async (formEl: FormInstance | undefined) => {
    
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log(ruleForm);
            ruleForm.status = 1;
            axios.post(apiUrl +'/T6/ProductInfos/AddProductionReport', ruleForm)
                .then(res => {
                    if (res.data.code == 100) {
                        ElMessage.success(res.data.msg);
                        dialogFormVisible.value = false;
                        fetchData();
                    } else {
                        ElMessage.error("添加失败!");
                    }
                });
        } else {
            console.log('error submit!', fields);
        }
    });
};

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
};

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}));

// 在页面挂载完成后调用 fetchData 方法
onMounted(() => {
    fetchData();
});
</script>
<style></style>